import {isNumber} from "ant-design-vue/es/_util/hooks/_vueuse/is";
import md5 from "md5";
import {buildCache} from "~/utils/Cache";
import Trans from "~/utils/sycm/trans";

const SYCMCache = buildCache('XC_SYCM', 'LIB_STORE_XCACHE_SYCM');
export default class SYCM {
    static toNumberIndex: string[] = [
        'lostIndex','crtByrCntIndex','lostHits','tradeIndex', 'seIpvUvHits','sePvIndex', 'uvIndex','clickHot', 'clickHits', 'avgWordSeIpvUvHits', 'avgWordClickHits', 'cartHits', 'cltHits', 'prePayAmtIndex', 'payByrCntIndex', 'uvHits', 'pvHot', 'cltHot', 'cartHot'
    ];
    static ToRatioIndex: string[] = [
        'payRateIndex', 'crtRateIndex'
    ]

    public static async getInternalFiberData(selector: string, field: string = ''): Promise<any> {
        return new Promise((resolve, reject) => {
            let sessionKey = md5('___' + selector + '-' + field + '-' + Date.now() + Math.random() + '___');
            let script = document.createElement('script');
            const listener = (ev: MessageEvent<any>) => {
                if (typeof ev.data.type !== 'undefined' && ev.data.type === 'xc_' + sessionKey) {
                    window.removeEventListener('message', listener);
                    if (ev.data.status === false) {
                        reject('获取数据失败');
                    } else {
                        try {
                            ev.data.message = JSON.parse(ev.data.message);
                        } catch (e) {
                            // console.log(e);
                        }
                        resolve(ev.data.message);
                    }
                    document.documentElement.removeChild(script);
                }
            };
            window.addEventListener('message', listener);
            script.type = 'text/javascript';
            script.id = sessionKey;
            script.innerHTML = `
            let dom_${sessionKey} = document.querySelector('${selector}');
            let stringifyWithoutCircular_${sessionKey} = (obj) => {
              const cache = new Set(); // 缓存已访问的对象
              return JSON.stringify(obj, (key, value) => {
                if (typeof value === 'object' && value !== null) {
                  // 检查是否存在循环引用
                  if (cache.has(value)) {
                    return; // 忽略循环引用
                  }
                  cache.add(value);
                }
                return value;
              });
            }
            if(dom_${sessionKey} == null){
                postMessage({type:'xc_${sessionKey}',message:null,status:true},'*');
            }else{
                try{
                    let key_${sessionKey} = Object.keys(dom_${sessionKey}).find(key=>key.startsWith("__reactInternalInstance$"));
                    let internalInstance_${sessionKey} = dom_${sessionKey}[key_${sessionKey}];
                    try{
                        postMessage({type:'xc_${sessionKey}',message:JSON.stringify(internalInstance_${sessionKey}${field == '' ? '' : '.' + field},(key,value)=>{  if (value instanceof Element || ['indexesTrendWrapper','stateNode','_context','Consumer','child','return','alternate','_owner'].indexOf(key)>-1) {return "[HIDE]";}return value;}),status:true},'*');
                    }catch(e){
                        try{
                            postMessage({type:'xc_${sessionKey}',message:stringifyWithoutCircular_${sessionKey}(internalInstance_${sessionKey}${field == '' ? '' : '.' + field}),status:true},'*');
                        }catch(e){
                            postMessage({type:'xc_${sessionKey}',message:null,status:true,error:e},'*');
                        }
                    }
                }catch(e){
                    postMessage({type:'xc_${sessionKey}',message:null,status:true,error:e},'*');
                }
            }
            delete stringifyWithoutCircular_${sessionKey};
            delete dom_${sessionKey};
            delete key_${sessionKey};
            delete internalInstance_${sessionKey};
        `;
            document.documentElement.appendChild(script);
        });
    }

    static async getItemRank() {
        let selector = '#sycm-cc-item-rank\\\\$opt-table > div.oui-card-content > div';
        let pagination = await SYCM.getInternalFiberData(selector, 'memoizedProps.children[5].props.children[1].props.children.props');
        const change = async (page: Number) => {
            return new Promise(async (resolve, reject) => {
                try {
                    let currData = await SYCM.getItemRank();
                    let data = currData.data;
                    let pageDom = document.querySelector('#sycm-cc-item-rank\\$opt-table > div.oui-card-content > div > div.alife-dt-card-common-table-pagination-container > div > ul > li[title="' + page + '"]');
                    if (pageDom != null) {
                        pageDom.click();
                    }
                    while (currData.pagination.current != page || JSON.stringify(currData.data) === JSON.stringify(data)) {
                        currData = await SYCM.getItemRank();
                    }
                    resolve(currData);
                } catch (e) {
                    reject(e);
                }
            });
        };
        if (!pagination) {
            pagination = {
                current: 1,
                total: 0,
                hasNext: false,
                change,
            };
        } else {
            pagination.change = change;
        }
        let data = await SYCM.getInternalFiberData(selector, 'memoizedProps.children[4].props.dataSource');
        if (pagination.total === 0) {
            pagination.total = data.length;
        }
        return {
            indexes: await SYCM.getInternalFiberData(selector, 'memoizedProps.children[1].props.children.props.indexes'),
            data: data,
            pagination: pagination,
        };
    }

    // 流量看板 流量总览 tab
    public static async flowMonitorOverviewTabs() {
        let selector = '#flow-overview-floor-summary > div > div > div.oui-card-content > div.alife-one-design-sycm-indexes-trend-index-content-container.summary-main-index-tab';
        return [
            {
                key: 0,
                active: ((await SYCM.getInternalFiberData(selector, 'memoizedProps.children[0].props.className')) || '').includes('active'),
                props: await SYCM.getInternalFiberData(selector, 'memoizedProps.children[0].props.children[0].props')
            },
            {
                key: 1,
                active: ((await SYCM.getInternalFiberData(selector, 'memoizedProps.children[1].props.className')) || '').includes('active'),
                props: await SYCM.getInternalFiberData(selector, 'memoizedProps.children[1].props.children[0].props')
            },
            {
                key: 2,
                active: ((await SYCM.getInternalFiberData(selector, 'memoizedProps.children[2].props.className')) || '').includes('active'),
                props: await SYCM.getInternalFiberData(selector, 'memoizedProps.children[2].props.children[0].props')
            }
        ];
    }

    public static async getFlowMonitorOverviewChildTabsChartData() {
        let selector = "#sycm-flow-overview-board-summary-indexes-trend > div.oui-card-content.alife-one-design-sycm-indexes-trend-card-content > div > div.alife-one-design-sycm-indexes-trend-chart-container > div > div";
        return await SYCM.getInternalFiberData(selector, 'memoizedProps.children.props');
    }

    public static async flowMonitorOverviewChildTabs() {
        let selector = '#sycm-flow-overview-board-summary-indexes-trend .alife-one-design-sycm-indexes-trend-card-content div.alife-one-design-sycm-indexes-trend-index-container > div > div';
        let data = await SYCM.getInternalFiberData(selector, 'memoizedProps.children');
        if (!data) {
            return null;
        }
        let results = [];
        for (let i = 0; i < data.length; i++) {
            for (let j = 0; j < data[i].props.children.length; j++) {
                let active = data[i].props.children[j].props.className.indexOf('active') > -1;
                let d: any = null;
                if (active) {
                    d = await this.getFlowMonitorOverviewChildTabsChartData();
                    while (typeof d.data === 'undefined') {
                        d = await this.getFlowMonitorOverviewChildTabsChartData();
                    }
                    // 设置缓存
                    await SYCMCache.set(md5(`FlowMonitorOverviewChildTabsChartData_${data[i].props.children[j].props.children[0].props.value}${data[i].props.children[j].props.children[0].props.numberValue}${JSON.stringify(data[i].props.children[j].props.children[0].props.subIndexes)}`), d, 60 * 60 * 24);
                } else {
                    d = await SYCMCache.get(md5(`FlowMonitorOverviewChildTabsChartData_${data[i].props.children[j].props.children[0].props.value}${data[i].props.children[j].props.children[0].props.numberValue}${JSON.stringify(data[i].props.children[j].props.children[0].props.subIndexes)}`));
                }
                results.push({
                    key: data[i].props.children[j].props.children[0].props.value,
                    name: data[i].props.children[j].props.children[0].props.text,
                    subIndexes: data[i].props.children[j].props.children[0].props.subIndexes,
                    numberValue: data[i].props.children[j].props.children[0].props.numberValue,
                    format: data[i].props.children[j].props.children[0].props.format,
                    active: active,
                    className: data[i].props.children[j].props.className,
                    data: d,
                });
            }
        }
        return results;
    }

    public static assignData(data: any[]) {
        data.map((item: any) => {
            ['tradeIndex','sePvIndex', 'clickHits', 'avgWordClickHits', 'avgWordSeIpvUvHits', 'uvIndex', 'seIpvUvHits', 'cltHits', 'cartHits', 'preTradeIndex'].map(index => {
                Object.keys(item).map(key => {
                    if (key.endsWith(index)) {
                        try {
                            if (isNumber(item[key])) {
                                item[`${key}_tran`] = Trans.number(item[key])
                            } else if (typeof item[key].value !== 'undefined') {
                                item[`${key}_tran`] = Trans.number(item[key].value || 0)
                            }
                        } catch (e) {
                            item[`${key}_tran`] = 0;
                        }
                    }
                })
            });
            ['RateIndex'].map(index => {
                Object.keys(item).map(key => {
                    if (key.endsWith(index)) {
                        try {
                            if (isNumber(item[key])) {
                                item[`${key}_tran`] = Trans.ratio(item[key])
                            } else if (typeof item[key].value !== 'undefined') {
                                item[`${key}_tran`] = Trans.ratio(item[key].value || 0)
                            } else {
                                item[`${key}_tran`] = 0 + '%';
                            }
                        } catch (e) {
                            item[`${key}_tran`] = 0 + '%';
                        }
                    }
                })
            })
            if (typeof item['tradeIndex'] !== 'undefined') {
                try {
                    item['tradeAmount'] = Trans.number(item.tradeIndex.value || 0);  // 交易金额
                } catch (e) {
                    item['tradeAmount'] = 0;
                }
            }
            if (typeof item['uvIndex'] !== 'undefined') {
                try {
                    item['uv'] = Trans.number(item.uvIndex.value || 0);              // 访问人数
                } catch (e) {
                    item['uv'] = 0;
                }
            }
            if (typeof item['seIpvUvHits'] !== 'undefined') {

                try {
                    item['seIpvUv'] = Trans.number(item.seIpvUvHits.value || 0);     // 搜索人数
                } catch (e) {
                    item['seIpvUv'] = 0;
                }
            }
            if (typeof item['cltHits'] !== 'undefined') {
                try {
                    item['clt'] = Trans.number(item.cltHits.value || 0);             // 收藏人数
                } catch (e) {
                    item['clt'] = 0;
                }
            }
            if (typeof item['cartHits'] !== 'undefined') {
                try {
                    item['cart'] = Trans.number(item.cartHits.value || 0);           // 加购人数
                } catch (e) {
                    item['cart'] = 0;
                }
            }
            if (typeof item['preTradeIndex'] !== 'undefined') {
                try {
                    item['payRate'] = Trans.ratio(item.payRateIndex.value);         // 支付转化率
                } catch (e) {
                    item['payRate'] = '0%';
                }
            }
            try {
                item['seRate'] = ((item['seIpvUv'] / item['uv']) * 100).toFixed(2) + '%';               // 搜索占比
                if (item['seRate'] == 'NaN%') {
                    item['seRate'] = '0%';
                }
            } catch (e) {
                item['seRate'] = '0%';
            }
            try {
                item['cltRate'] = ((item['clt'] / item['uv']) * 100).toFixed(2) + '%'                   // 收藏率
                if (item['cltRate'] == 'NaN%') {
                    item['cltRate'] = '0%';
                }
            } catch (e) {
                item['cltRate'] = '0%';
            }
            try {                                                                                         // 加购率
                item['cartRate'] = ((item['cart'] / item['uv']) * 100).toFixed(2) + '%';
                if (item['cartRate'] == 'NaN%') {
                    item['cartRate'] = '0%';
                }
            } catch (e) {
                item['cartRate'] = '0%';
            }
            try {
                item['cartCltRate'] = ((parseFloat(item['cartRate']) + parseFloat(item['cltRate']))).toFixed(2) + '%';     // 收藏加购率
                if (item['cartCltRate'] == 'NaN%') {
                    item['cartCltRate'] = '0%';
                }
            } catch (e) {
                item['cartCltRate'] = '0%';
            }
            try {
                item['uvAmount'] = (item['tradeAmount'] / item['uv']).toFixed(2);       // UV价值
                if (item['uvAmount'] == 'NaN') {
                    item['uvAmount'] = '0';
                }
            } catch (e) {
                item['uvAmount'] = 0;
            }
            try {
                if (typeof item['clickHits_tran'] !== 'undefined' && typeof item['payRate'] !== 'undefined') {
                    item['payUserNumber'] = parseInt(String(item['clickHits_tran'] * (parseFloat(item['payRate']) / 100)));       // 支付买家数
                } else if (typeof item['uvIndex_tran'] !== 'undefined' && typeof item['payRateIndex_tran'] !== 'undefined') {
                    item['payUserNumber'] = parseInt(String(item['uvIndex_tran'] * (parseFloat(item['payRateIndex_tran']) / 100)));       // 支付买家数
                }
            } catch (e) {
                item['payUserNumber'] = 0;
            }
            try {
                if (item['payUserNumber'] == 0) {
                    item['customerUnitPrice'] = 0;
                } else {
                    item['customerUnitPrice'] = (item['tradeAmount'] / item['payUserNumber']).toFixed(2);       // 客单价
                    if (item['customerUnitPrice'] == 'NaN') {
                        item['customerUnitPrice'] = 0;
                    }
                }
            } catch (e) {
                item['customerUnitPrice'] = 0;
            }
        });
    }
}

export {SYCMCache};
